package com.xinruke.hostels.support.job;

import com.xinruke.hostels.common.cache.base.factory.CacheFactory;
import com.xinruke.hostels.common.cache.base.interfaces.ICache;
import com.xinruke.hostels.support.common.cache.PushQueueUtil;
import com.xinruke.hostels.support.service.cache.SysCodeCacheImpl;
import com.xinruke.hostels.support.service.cache.XtZidianSqlParamCacheImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @ClassName ScanRedisMsgFlushSystemDicJob
 * @CreateDate 2019/7/27
 * @Author chenry
 * @Version V1.0.0.0
 * @Decription 系统字典参数刷新定时任务
 */
@Component
public class ScanRedisMsgFlushSystemDicJob {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${flushSystemDicMsgSend.open}")
    private String taskOpen;

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private XtZidianSqlParamCacheImpl xtZidianSqlParamCacheImpl;

    @Autowired
    private SysCodeCacheImpl sysCodeCacheImpl;

    @Autowired
    private Map<String, ICache> caches;

    private boolean isInitTask = true;

    @Scheduled(cron = "${flushSystemDicMsgSend.cron}")
    public void sendMessage() {
//        if (caches == null) {
//            logger.info("开始初始刷缓存========================");
//            caches = (Map<String, ICache>) ApplicationContextHelper.getBean(ICache.class);
//            fushAllCache(caches);
//        }
        if (isInitTask) {
            logger.info("开始初始刷缓存========================");
            isInitTask = false;
            fushAllCache(caches);
            return;
        }
        if ("1".equals(taskOpen)) {
            if (PushQueueUtil.getFushCacheMsgInReids() != null) {
                logger.info("刷缓存========================");
                fushAllCache(caches);
            }
        } else {
            logger.error("ScanRedisMsgFlushSystemDicJob  系统字典参数刷新定时任务未开启！");
        }
    }


    public static void fushAllCache(Map<String, ICache> caches) {
        for (ICache cache : caches.values()) {
            CacheFactory.remove(cache.getKey());
            CacheFactory.putData(cache);
        }
    }

}
